﻿using System;
using System.IO;
using System.Linq;
using System.Web;

namespace WebCommon.Up
{
    /// <summary>
    /// 使用API文件上传
    /// </summary>
    public class ApiUp
    {
        enum Days { Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday };
        private HttpPostedFile _file;
        /// <summary>
        /// 文件名
        /// </summary>
        public string No { get; set; }
        /// <summary>
        /// 路径
        /// </summary>
        public string SaPath { get; set; }
        /// <summary>
        /// 是否保存扩展名
        /// </summary>
        private bool _isex;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="file">file</param>
        /// <param name="isex">是否获取扩展名</param>
        public ApiUp(HttpPostedFile file, bool isex = false) : this()
        {
            this._file = file;
        }
        

        protected ApiUp()
        {
            var dt = DateTime.Now;
            SaPath = $"upload/{dt.ToString("yyyy")}/{dt.ToString("MMdd")}/";
            ServerPath = HttpContext.Current.Server.MapPath($"~/{SaPath}");
            if (!Directory.Exists(SaPath))
            {
                Directory.CreateDirectory(ServerPath);
            }
          
            No = Guid.NewGuid().ToString("N")+WebCommon.Com.RandomsAzNum.GetLn(4) ;
        }

        public string ServerPath { get;protected set; }

        public virtual string Save()
        {
            try
            {
                var ex = string.Empty;
                if (_isex)
                {
                    var fileName = _file.FileName;
                    ex = System.IO.Path.GetExtension(fileName);
                }
                _file.SaveAs(ServerPath + No + ex);
            }
            catch (Exception exception)
            {
                return exception.Message;
                
            }

            return String.Empty; ;
        }
        /// <summary>
        /// 判断类型
        /// </summary>
        /// <returns></returns>
        public bool IsType(string[] extensions)
        { 
            if (extensions != null)
            {
                return extensions.Any(x => FileExtension == x);

            }
            return true;
        }

        /// <summary>
        /// 获取扩展名
        /// </summary>
        public virtual string FileExtension
        {
            get
            {
                var extension = Path.GetExtension(this._file.FileName);
                return extension.ToLower();
            }
        }

        /// <summary>
        /// 图片通过的合法扩展名
        /// </summary>
        public static string[] ImgTypeList =  { ".jpg", ".png", ".gif", ".jpeg" };
        /// <summary>
        /// 压缩通过的合法扩展名
        /// </summary>
        public static string[] RarTypeList =  {".rar",".zip"};
        /// <summary>
        /// TXT通过的合法扩展名
        /// </summary>
        public static string[] TxtTypeList =  {".txt"};
    }
}